<template>
  <div class="app-container pg-waybill-list">
    <!-- el-tabs begin -->
    <div ref="pageTab" class="page-tab-box">
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="(item, index) in tabList" :key="`tab-${index}`" :name="item.name">
          <div class="tab-label" slot="label">
            <span class="label-name">{{ item.label }}</span>
            <span v-if="item.name=='returned'" class="label-tip bg_red">{{ item.quantity }}</span>
            <span class="label-tip" v-else>{{ item.quantity }}</span>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div v-if="activeName=='delete'" class="page-tab-child">
        <el-radio-group class="tab-child-group" v-model="activeChildName">
          <el-radio-button :label="90">
            <span class="tab-child-name">待审核</span>
            <span class="number">{{ waybillQuantity.waitAuditDeleteQuantity }}</span>
          </el-radio-button>
          <el-radio-button :label="100">
            <span class="tab-child-name">已删除</span>
            <span class="color-red number">{{ waybillQuantity.successDeleteQuantity }}</span>
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <!-- el-tabs end -->
    <!-- top-search begin -->
    <div ref="topSearch" class="top-search top-more-search" v-show="showSearch">
      <el-form
        inline
        ref="searchForm"
        label-width="0"
        class="search-form"
        :class="{ 'show-more': showFormMore }"
        :model="searchForm">
        <el-form-item prop="cusId">
          <el-select v-model="searchForm.cusId" placeholder="客户名称" clearable @change="search()">
            <el-option label="客户1" value="1"></el-option>
            <el-option label="客户2" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="productId">
          <el-select v-model="searchForm.productId" placeholder="运输产品" clearable @change="search()">
            <el-option label="产品1" value="1"></el-option>
            <el-option label="产品2" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="cusIdOrder">
          <el-input v-model="searchForm.activeNo" placeholder="请输入" clearable @keyup.enter.native="search()">
            <el-select class="w-100" v-model="searchForm.cusIdOrder" slot="prepend" placeholder="请选择" @change="search()">
              <el-option label="客户单号" value="orderNo"></el-option>
              <el-option label="转单号" value="carrierBustNo"></el-option>
              <el-option label="运单号" value="waybillNo"></el-option>
              <el-option label="PO单号" value="waybillEntrustNo"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <el-form-item prop="boxNo">
          <el-input v-model="searchForm.activeCode" placeholder="请输入" clearable @keyup.enter.native="search()">
            <el-select class="w-85" v-model="searchForm.boxNo" slot="prepend">
              <el-option label="箱号" value="bagsCode"></el-option>
              <el-option label="主单号" value="carrierBillNo"></el-option>
            </el-select>
          </el-input>
        </el-form-item>
        <div class="search-more-item" v-show="isBigWindow || showFormMore">
          <div class="append-item">
            <el-form-item prop="activeTime" class="append-l w-100">
              <el-select ref="timeSelect" v-model="searchForm.activeTime">
                <el-option label="发货日期" value="dateRange"></el-option>
                <el-option label="入库日期" value="dateRange1"></el-option>
                <el-option label="出库日期" value="dateRange2"></el-option>
                <el-option label="主单日期" value="dateRange3"></el-option>
                <el-option label="到达海外仓" value="dateRange4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="dateRange" class="append-r">
              <el-date-picker v-model="searchForm.dateRange" type="daterange" unlink-panels range-separator="-"
                start-placeholder="下单开始日期" end-placeholder="下单截止日期" value-format="yyyy-MM-dd HH:mm:ss" clearable
                :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']" @change="search()">
              </el-date-picker>
            </el-form-item>
          </div>
        </div>
        <div class="search-more-item" v-show="showFormMore">
          <el-form-item prop="carrierId">
            <el-select v-model="searchForm.carrierId" placeholder="下家名称" clearable @change="search()">
              <el-option label="下家1" value="1"></el-option>
              <el-option label="下家2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="carrierId">
            <el-select v-model="searchForm.carrierId" placeholder="渠道(可多选)" clearable @change="search()">
              <el-option label="下家1" value="1"></el-option>
              <el-option label="下家2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="isError">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isError"
              clearable
              placeholder="是否异常"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="waybillTrackStatus">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.waybillTrackStatus"
              clearable
              placeholder="跟踪状态"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="hasTransferNo">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.hasTransferNo"
              clearable
              placeholder="是否有转单号"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="hasLastLeg">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.hasLastLeg"
              clearable
              placeholder="是否有尾程面单"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="isScanned">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isScanned"
              clearable
              placeholder="是否扫描打印"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="isIntercepted">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isIntercepted"
              clearable
              placeholder="是否拦截"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="waybillSource">
            <dg-dict-select
              dictType="waybill_source"
              v-model="searchForm.waybillSource"
              clearable
              placeholder="运单来源"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="consigneeStoreName">
            <el-input v-model="searchForm.consigneeStoreName" placeholder="平台店铺" @keyup.enter.native="search()" />
          </el-form-item>
          <el-form-item prop="hasReceivable">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.hasReceivable"
              clearable
              placeholder="是否有应收"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="isReceivableAccounted">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isReceivableAccounted"
              clearable
              placeholder="应收是否做账"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="isReceivableAccounted">
            <el-select v-model="searchForm.isReceivableAccounted" placeholder="应收账单状态" @change="search()">
              <el-option label="状态1" value="1"></el-option>
              <el-option label="状态2" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="receivableNo">
            <el-input v-model="searchForm.receivableNo" placeholder="应收账单号" @keyup.enter.native="search()" />
          </el-form-item>
          <el-form-item prop="isForecast">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isForecast"
              clearable
              placeholder="是否预报"
              @change="search()" />
          </el-form-item>
        </div>
        <el-form-item class="search-btn-part">
          <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery()">重置</el-button>
          <el-button class="more-btn" type="text" @click="searchShowMore()">{{ !showFormMore ? '更多' : '收起'
          }}<span class="ml5" :class="`el-icon-arrow-${!showFormMore ? 'down' : 'up'}`"></span></el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- top-search end -->
    <!-- right-toolbar begin -->
    <right-toolbar ref="rightToolbar" :showSearch.sync="showSearch" @queryTable="search()">
      <template v-slot:operaBar>
        <template v-if="activeName=='all'">
          <el-button type="primary" @click="handleShow()">创建运单</el-button>
          <el-button type="primary" @click="handleUpload()">导入运单</el-button>
        </template>
        <el-dropdown v-if="activeName!='delete'" class="toolbar-btn">
          <el-button type="primary" plain>
            下载面单<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="downLoadLabel()">下载尾程面单</el-dropdown-item>
            <el-dropdown-item @click.native="print()">面单预览打印</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <template v-if="activeName=='all'||activeName=='draft'">
          <el-button type="primary" plain @click="updateWaybillProduct()">修改运输产品</el-button>
          <el-button type="primary" plain @click="updatePickupDate()">
            到达海外仓
            <el-tooltip effect="dark" placement="top" content="海外仓入库时间">
              <span class="tip-icon el-icon-question"></span>
            </el-tooltip>
          </el-button>
          <el-button type="primary" plain @click="uploadCarrierBusNo()">上传转单号及label</el-button>
        </template>
        <template v-if="activeName!='draft'&&activeName!='delete'">
          <dg-import-excel type="primary" refresh @refresh="search" name="导入应收">
            <template slot="excel">
              <div class="mt10 text-center">只能上传xlsx文件，<a class="page-link" href="" target="_blank">点击下载导入模板</a>
              </div>
            </template>
          </dg-import-excel>
          <el-button type="primary" plain @click="caulate()">应收计算</el-button>
          <el-dropdown class="toolbar-btn">
            <el-button type="primary" plain>
              生成应收账单<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="createCusVouch()">勾选运单生成账单</el-dropdown-item>
              <el-dropdown-item @click.native="quickCusVouch()">按客户/日期生成账单</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button type="primary" plain @click="caulateCarrier()">应付计算</el-button>
          <el-button type="primary" plain @click="createCarrierVouch()">生成应付账单</el-button>
          <el-button type="primary" plain @click="showTrack()">批量跟踪</el-button>
        </template>
        <el-button v-if="activeName!='delete'" type="primary" plain @click="confirmOrder()">预报确认</el-button>
        <el-button v-if="activeName=='confirm'" type="primary" plain @click="confirmInStore()">批量入库确认</el-button>
        <el-dropdown v-if="activeName!='delete'" class="toolbar-btn">
          <el-button type="primary" plain>
            标记异常<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="addError()">标记异常</el-dropdown-item>
            <el-dropdown-item @click.native="solveOrderError(selectIds,search)">取消异常</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button v-if="activeName!='send'&&activeName!='sign'&&activeName!='delete'" type="danger" plain @click="del()">删除运单</el-button>
        <el-button v-if="activeName=='delete'&&activeChildName==90" type="primary" @click="auditWaybill()">审核</el-button>
        <el-dropdown class="toolbar-btn">
          <el-button type="primary" plain>
            导出<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="handleExport(true)">运单费用导出</el-dropdown-item>
            <el-dropdown-item>
              <dg-template-export class="toolbar-dropdown-btn" type="text" name="自定义导出(含财务信息)"
                code="EXPORT_MANAGE_WAYBILL" :needParams="true"
                :exportIds="selectIds" @getParams="getExportParams"></dg-template-export>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </right-toolbar>
    <!-- right-toolbar end -->
    <!-- table begin -->
    <el-table ref="pageTable" class="page-table border-all mt10"
      :data="tableData" :row-key="getRowKeys"
      @selection-change="tableSelect"
      show-summary :summary-method="getSummaries"
      :height="tableHeight" border stripe>
      <el-table-column type="selection" width="32" fixed></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillEntrustNo" label="客户单号" width="118" align="center" fixed></el-table-column>
      <el-table-column show-overflow-tooltip prop="errorDescription" label="异常" width="108" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillTrackStatus" label="状态" width="72" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="cusAbbName" label="客户名称" width="118" align="center" sortable></el-table-column>
      <el-table-column show-overflow-tooltip prop="carrierBustNo" label="转单号" width="76" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillDate" label="发货日期" width="98" align="center" sortable></el-table-column>
      <el-table-column show-overflow-tooltip prop="productName" label="运输产品" width="118" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="goodsWeight" label="预报重kg" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="goodsActWeight" label="实重kg" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="billTrafic" label="计费重kg" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="shipperTaxnocountry" label="国家" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="goodsNameZh" label="中文名" width="98" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="billingWeight" label="英文名" width="98" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="estimateCost" label="货值" width="76" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="goodsHscode" label="HSCode" width="98" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="inboundDate" label="入库时间" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="carrierBillNo" label="运单号" width="98" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="outboundDate" label="出库时间" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="onLineTime" label="上网时间" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="signTime" label="签收时间" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltipprop="receAndSignDays" label="收货-签收" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltipprop="onLineAndSignDays" label="上网-签收" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltipprop="outBoundAndSignDays" label="出货-签收" width="88" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="ediMessage" label="对接信息" width="150" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillEntrustNo" label="PO单号" width="138" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeStoreName" label="平台店铺" width="138" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeCity" label="城市" width="78" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillTrackContent" label="最新轨迹" width="128" align="center"></el-table-column>
      <el-table-column show-overflow-tooltip prop="waybillTrackDate" label="轨迹时间" width="138" align="center" sortable></el-table-column>
      <el-table-column show-overflow-tooltip prop="totalCost" label="运费" width="78" align="center"></el-table-column>
      <el-table-column label="操作" width="60" fixed="right">
        <template slot-scope="scope">
          <div class="opera-row">
            <!-- 编辑按钮 -->
            <el-tooltip content="编辑" placement="top">
              <el-button class="opera-item icon-opera-item" type="text" icon="el-icon-edit-outline" @click="editCustomer(scope.row)"></el-button>
            </el-tooltip>
            <!-- 更多操作悬停菜单 -->
            <el-dropdown trigger="hover" @command="handleCommand($event, scope.row)">
              <el-button class="opera-item icon-opera-item" type="text" icon="el-icon-more"></el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="bindWareHouse">跟踪</el-dropdown-item>
                <el-dropdown-item command="bindCarryProduct">应收</el-dropdown-item>
                <el-dropdown-item command="accountManage">应付</el-dropdown-item>
                <el-dropdown-item command="getApiInfo">复制</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- table end -->
    <!-- page-pagination begin -->
    <pagination
      class="page-pagination"
      :total="total"
      :page-size="pageSize"
      :page-index="pageIndex"
      @change="pageChange">
    </pagination>
    <!-- page-pagination end -->
  </div>
</template>

<script>
import mixin from '@/utils/filtermixin/mixin';
import listmixin from '@/utils/list-mixin';
import { Foundation } from '@/utils/index';
import * as API_Waybill  from '@/api/tmsystem/waybill';
import * as API_Track  from '@/api/tmsystem/track';
import * as API_Expense  from '@/api/tmsystem/expense';

export default {
  name: 'pg-waybill-list',
  dicts: [],
  mixins: [mixin, listmixin],
  data () {
    return {
      // tab
      tabList: [
        { label: '全部运单', name: 'all', quantity: 0 },
        { label: '确认运单', name: 'confirm', quantity: 0 },
        { label: '已入库', name: 'receive', quantity: 0 },
        { label: '已出库', name: 'send', quantity: 0 },
        { label: '已签收', name: 'sign', quantity: 0 },
        { label: '对接失败', name: 'draft', quantity: 0 },
        { label: '已删除', name: 'delete', quantity: 0 }
      ],
      activeName: 'all',
      activeChildName: 90,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      searchForm: {
        // 搜索
        cusId: undefined,
        orderNo: undefined,
        carrierBustNo: undefined,
        waybillNo: undefined,
        dateRange: [],
        waybillTrackStatus: undefined,
        productId: undefined,
        consigneeCountry: undefined,
        consigneeState: undefined,
        consigneeCity: undefined,
        consigneePostcode: undefined,
        carrierId: undefined,
        carrierChannelIdList: [],
        carrierBillNo: undefined,
        chargeOrgName: undefined,
        isCod: undefined,
        waybillCusVouchStatus: undefined,
        waybillCarrierVouchStatus: undefined,
        waybillStatus: undefined,
        waybillSource: undefined,
        waybillType: undefined,
        remarks: undefined,
        bagsCode: undefined,
        predictionStatus: undefined,
        isPrediction: undefined,
        dateRange1: [],
        dateRange2: [],
        dateRange3: [],
        dateRange4: [],
        isMarkedError: undefined,
        isHadPrint: undefined,
        waybillEntrustNo: undefined,
        isHadLabel: undefined,
        isIntercept: undefined,
        isHadCarrierBustNo: undefined,
        consigneeStoreName: undefined,
        isHadCusCost: undefined,
        isCusVouch: undefined,
        customerVouchCode: undefined,
        isHadCarrierCost: undefined,
        isCarrierVouch: undefined,
        carrierVouchCode: undefined
      },
      tableData: [],
      // 获取row的key值
      getRowKeys (row) {
        return row.id;
      },
      selectIds: [],
      selectRows: [],

      // 分页属性
      total: 0, // 记录总条数
      pageSize: 20, // 每页显示条数
      pageIndex: 1 // 当前页
    };
  },
  watch: {
    /**
     * @date 2025/07/15
     * @author wolfMan
     * @description {tab 切换}
     */
    activeName() {
      this.search();
    }
  },
  created () {
    // 设置最近 3 天时间
    let start = new Date().getTime() - 3600 * 1000 * 24 * 2;
    start = `${Foundation.unixMillToDate(start).split(' ')[0]} 00:00:00`;
    let end = `${Foundation.unixMillToDate(new Date()).split(' ')[0]} 23:59:59`;
    this.searchForm.dateRange = [
      Foundation.unixMillToDate(start),
      Foundation.unixMillToDate(end)
    ];
  },
  mounted () {
    // 获取页面数据
    this.search();
  },
  methods: {
    /**
      * @date 2025/07/08
      * @author wolfMan
      * @description {页面查询}
    */
    search (_type) {
      let _params = this.MixinFilterParams(this.MixinClone(this.searchForm));
      if (_params.dateRange && _params.dateRange.length) {
        _params.startCreateTime = _params.dateRange[0];
        _params.endCreateTime = _params.dateRange[1];
      };
      delete _params.dateRange;
      // if (!_params.alOrderInput) {
      //   delete _params.alOrderType;
      // };
      // if (!_params.receiverInput) {
      //   delete _params.receiverType;
      // };
      // _params.tabStatus = this.activeName;
      // 重置分页
      if (_type !== 'selectPage') {
        this.pageIndex = 1; // 重置翻页当前页
      };
      this.getPageData(_params);
      // 获取页面统计数据
      // this.getPageTotal(_params);
    },
    /**
      * @date 2025/07/15
      * @author wolfMan
      * @description {获取页面数据}
    */
    getPageData (params) {
      let _params = {
        ...params,
        pageNum: this.pageIndex,
        pageSize: this.pageSize
      };
      API_Waybill.getListService(_params).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
      });
    },
    /**
      * @date 2025/07/15
      * @author wolfMan
      * @description {表格行选中}
    */
    getSummaries (param) {
      this.$nextTick(() => {
        this.$refs.pageTable.doLayout();
      });
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        var sumColumnArray = [
          'waybillPiece',
          'goodsWeight',
          'goodsActWeight',
          'billTrafic',
          'totalCost',
          'totalCarrierCost',
          'totalCodAmount',
          'estimateCost'
        ];
        if (sumColumnArray.indexOf(column.property) > -1) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              };
            }, 0);
            if (column.property == 'waybillPiece'){
              sums[index] = sums[index].toFixed(0);
            } else {
              sums[index] = sums[index].toFixed(3);
            };
          };
        } else {
          sums[index] = '';
        };
      });
      return sums;
    },
    /**
      * @date 2025/07/15
      * @author wolfMan
      * @description {表格行选中}
    */
    tableSelect(_row) {
      this.selectedIds = _row.map((item) => item.id);
      this.selectedRows = _row;
    },
    /**
      * @date 2025/07/15
      * @author wolfMan
      * @description {获取自定义模板导出参数}
    */
    getExportParams (callback) {
      let _params = this.MixinFilterParams(this.MixinClone(this.searchForm));
      if (_params.createDateRange && _params.createDateRange.length) {
        _params.startCreateTime = _params.createDateRange[0];
        _params.endCreateTime = _params.createDateRange[1];
      }
      delete _params.createDateRange;
      _params.tabStatus = this.activeName;
      callback(_params);
    },

    handleGz(row) {
      this.dialogVisible = true;
      this.trackNumber = row.id;
      this.receiverAddress = row.waybillTransactionurl;
      this.getTrackList(row.id);
      console.log("跟踪订单:", row);

    },
    handleEdit(row) {
      // 跳转到详情页面
      this.$router.push({
        name: 'TmsOrderEdit',
        params: { id: row.id }
      });
    },
    handleDelete() {
      if (this.selectedRows1.length === 0) {
        this.$message.warning('请先选择要删除的数据');
        return;
      }
      const ids = this.selectedRows1.map(row => row.id);
      console.log('要删除的 ID 列表:', ids);
      this.$modal.confirm('是否确认删除运费用编号为"' + ids + '"的数据项？').then(function() {
        return API_Expense.delService(ids);
      }).then(() => {
        this.dialogVisible =false;
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        this.$message.info('已取消删除操作');
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      console.log("选中行:", selection);
    },
    getTrackList(id) {
      this.trackQueryParams.waybillId = id;
      API_Track.getListService(this.trackQueryParams).then(response => {
        console.log(response);
        this.trackList = response.rows;
      });
    },
    handleCommand(command, row) {
      console.log('执行命令:', command, row);
      switch (command) {
        case 'copy':
          this.handleCopy(row);
          break;
        case 'receivable':
          this.handleReceivable(row);
          break;
        case 'payable':
          this.handlePayable(row);
          break;
        default:
          console.log('未知命令');
      }
    },
    handleCopy(row) {
      // 跳转到详情页面
      this.$router.push({
        name: 'TmsCopy',
        params: { id: row.id }
      });

      console.log('复制操作');
      // 在这里添加复制逻辑
    },
    handleReceivable(row) {
      this.dialogVisible2 = true;
      this.form.waybillId = row.id;
      this.form.isDue = 0;
      this.form.waybillNo = row.waybillNo;
      this.getExpenseList(row.id,row.waybillNo);
      console.log('应收操作',this.form.waybillId,this.form.waybillNo);
      // 在这里添加应收逻辑
    },
    handlePayable(row) {
      this.dialogVisible2 = true;
      this.form.waybillId = row.id;
      this.form.isDue = 1;
      this.form.waybillNo = row.waybillNo;
      this.getExpenseList(row.id,row.waybillNo);
      console.log('应付操作',this.form.waybillId,this.form.waybillNo);
      // 在这里添加应付逻辑
    },
    trackAdd(){
      this.dialogVisible1 = true;
    },
    handleTrackSubmit(){
      this.trackForm.waybillId = this.trackQueryParams.waybillId;
      API_Track.addService(this.trackForm).then(() => {
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible1 = false;
        this.getTrackList(this.trackQueryParams.waybillId);
      });
    },
    handleTrackCancel(){
      this.dialogVisible1 = false;
    },
    getExpenseList(id,waybillNo) {
      this.expenseQueryParams.waybillId = id;
      this.expenseQueryParams.isDue = this.form.isDue;
      this.expenseQueryParams.waybillNo = waybillNo;
      API_Expense.getListService(this.expenseQueryParams).then(response => {
        console.log(response);
        this.expenseList = response.rows;
      });
    },
    handleSelectionChange1(selection) {
      this.selectedRows1 = selection;
      console.log("选中运费行:", selection);
    },
    handleSelectionChange2(selection) {
      this.selectedRows2 = selection;
      console.log("选中运费行:", selection);
    },
    handleAdd(){
      // 重置表单
      this.form = {
        priceType: '',
        priceAmount: null,
        priceUnit: null,
        priceCount: '',
        remark: '',
        chargeVolumeError: false,
        chargeRateError: false
      };
      this.isEditMode = false;
      this.editRowIndex = -1;
      this.innerDialogVisible = true;
      this.form.waybillId = this.expenseQueryParams.waybillId;
      this.form.isDue = this.expenseQueryParams.isDue;
      this.form.waybillNo = this.expenseQueryParams.waybillNo;
    },
    handleUpd(){
      if (this.selectedRows1.length === 0) {
        this.$message.warning('请先选择要修改的数据');
        return;
      }
      if (this.selectedRows1.length > 1) {
        this.$message.warning('只能选择一条数据进行修改');
        return;
      }

      const row = this.selectedRows1[0];
      this.form = { ...row };
      this.isEditMode = true;
      this.editRowIndex = this.freightData.findIndex(item => item.id === row.id);
      this.innerDialogVisible = true;
    },
    handleCancel(){

    },
    handleSubmit(){
      this.$refs.form.validate(valid => {
        if (valid) {
          // 计算费用合计
          this.form.priceCount = (
            this.form.priceAmount * this.form.priceUnit
          ).toFixed(2);

          if (this.isEditMode) {
            // 修改模式
            API_Expense.updateService(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getExpenseList(this.form.waybillId,this.form.waybillNo);
            });
            //this.$message.success('修改运费成功')
          } else {
            // 新增模式
            API_Expense.addService(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getExpenseList(this.form.waybillId,this.form.waybillNo);
            });
            //this.$message.success('新增运费成功')
          }

          this.innerDialogVisible = false;
        }
      });
    },
    // 验证计费单价输入
    validateChargeRate(rule, value, callback) {
      if (!this.form.priceUnit && this.form.priceUnit !== 0) {
        this.form.chargeRateError = true;
        callback(new Error('请输入计费单价'));
      } else if (isNaN(this.form.priceUnit)) {
        this.form.chargeRateError = true;
        callback(new Error('请输入有效的计费单价'));
      } else {
        this.form.chargeRateError = false;
        callback();
      }
    },
    // 验证输入
    validateInput(field) {
      if (field === 'priceAmount' && isNaN(this.form.priceAmount)) {
        this.form.chargeVolumeError = true;
        this.form.priceAmount = null;
      } else {
        this.form.chargeVolumeError = false;
      }

      if (field === 'priceUnit' && isNaN(this.form.priceUnit)) {
        this.form.chargeRateError = true;
        this.form.priceUnit = null;
      } else {
        this.form.chargeRateError = false;
      }

      // 计算费用合计
      this.calculateTotalCost();
    },
    // 计算费用合计
    calculateTotalCost() {
      if (
        this.form.priceAmount !== null &&
        this.form.priceUnit !== null &&
        !isNaN(this.form.priceAmount) &&
        !isNaN(this.form.priceUnit)
      ) {
        this.form.priceCount = (
          this.form.priceAmount * this.form.priceUnit
        ).toFixed(2);
      } else {
        this.form.priceCount = '';
      }
    }
  }
};
</script>